library(reticulate)

use_condaenv('scanpy')

np <- import('numpy')
ad <- import('anndata')
pd <- import('pandas')

py_run_string('from scipy.sparse import csr_matrix') # compressed sparse row mtx

# 100 cells x 2000 genes
py_run_string('counts = csr_matrix(np.random.poisson(1, size=(100, 2000)), dtype=np.float32)',convert = FALSE)
adata = ad$AnnData(py$counts)
adata

adata$X

# access obs_names & var_names
adata$obs_names = py_eval('[f"Cell_{i:d}" for i in range(adata.n_obs)]')
adata$var_names = py_eval('[f"Gene_{i:d}" for i in range(adata.n_vars)]')
adata$obs_names[1:10]

ct = py_eval('np.random.choice(["B", "T", "Monocyte"], size=(adata.n_obs,))')
adata$obs["cell_type"] = py_eval("pd.Categorical(ct)")  # Categoricals are preferred for efficiency, like factor in R?
adata$obs

bdata = py_eval('adata[adata.obs.cell_type == "B"]')

adata.obsm["X_umap"] = np.random.normal(0, 1, size=(adata.n_obs, 2))
adata.varm["gene_stuff"] = np.random.normal(0, 1, size=(adata.n_vars, 5))
adata.obsm